package com.example.mainexam2022110341

import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.icu.util.Calendar
import android.os.Bundle
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.gridlayout.widget.GridLayout


class MonthActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_month)

        // 设置 Toolbar
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayShowTitleEnabled(false) // 隐藏默认标题

        // 获取传递过来的数据
        val month = intent.getIntExtra("month", 0)
        val year = intent.getIntExtra("year", 0)
        val earliestYear = intent.getIntExtra("earliestYear", 0)
        val maxYear = intent.getIntExtra("maxYear", 0)
        val scrollPosition = intent.getIntExtra("scrollPosition", 0)

        // 设置返回按钮
        val backButton: TextView = findViewById(R.id.toolbar_back_button)
        backButton.text = "< ${year}年"
        backButton.setOnClickListener {
            // 使用 Intent 返回到 MainActivity
            val intent = Intent(this, YearActivity::class.java)
            intent.putExtra("earliestYear", earliestYear)
            intent.putExtra("maxYear", maxYear)
            intent.putExtra("scrollPosition", scrollPosition)
            intent.putExtra("isfirstRun", false)
            startActivity(intent)
            finish()
        }

        // 设置返回按钮点击颜色变化
        backButton.setOnTouchListener { v, event ->
            when (event.action) {
                android.view.MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                }
                android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                    v.setBackgroundColor(Color.TRANSPARENT) // 松开时恢复背景颜色
                }
            }
            false
        }

        // 设置月份标题
        val monthText: TextView = findViewById(R.id.month_title)
        monthText.text = "${month + 1}月" // month 是从 0 开始的，所以需要加 1
        monthText.setTypeface(null, Typeface.BOLD)

        // 设置星期几的标识
        val weekdayContainer: LinearLayout = findViewById(R.id.weekday_container)
        val daysOfWeek = arrayOf("日", "一", "二", "三", "四", "五", "六")
        for (day in daysOfWeek) {
            val textView = TextView(this)
            textView.text = day
            textView.textSize = 18f
            textView.gravity = Gravity.CENTER
            val params = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
            textView.layoutParams = params
            weekdayContainer.addView(textView)
        }

        // 设置 GridLayout
        val calendarGrid: GridLayout = findViewById(R.id.calendar_grid)
        calendarGrid.removeAllViews()
        //算生肖并设置背景图片
        val zodiac = getZodiac(year)
        val backgroundResource = when (zodiac) {
            "鼠" -> R.drawable.mouse
            "牛" -> R.drawable.cow
            "虎" -> R.drawable.tiger
            "兔" -> R.drawable.rabbit
            "龙" -> R.drawable.dragon
            "蛇" -> R.drawable.snake
            "马" -> R.drawable.horse
            "羊" -> R.drawable.goat
            "猴" -> R.drawable.monkey
            "鸡" -> R.drawable.chicken
            "狗" -> R.drawable.dog
            "猪" -> R.drawable.pig
            else -> R.drawable.monkey
        }
        calendarGrid.setBackgroundResource(backgroundResource)

        // 设置日历
        val calendar = Calendar.getInstance()
        val currentYear = calendar.get(Calendar.YEAR)
        val currentMonth = calendar.get(Calendar.MONTH)
        val currentDay = calendar.get(Calendar.DAY_OF_MONTH)
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, month)
        calendar.set(Calendar.DAY_OF_MONTH, 1)
        val firstDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1
        val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)


        // 添加第一条分隔线
        val firstDivider = View(this)
        val firstDividerParams = GridLayout.LayoutParams()
        firstDividerParams.rowSpec = GridLayout.spec(0)
        firstDividerParams.columnSpec = GridLayout.spec(0, 7)
        firstDividerParams.width = GridLayout.LayoutParams.MATCH_PARENT
        firstDividerParams.height = 4 // 分隔线高度
        firstDivider.setBackgroundColor(resources.getColor(android.R.color.darker_gray))
        firstDivider.layoutParams = firstDividerParams
        calendarGrid.addView(firstDivider)

        // 添加空白占位符
        for (i in 0 until firstDayOfWeek) {
            val textView = TextView(this)
            val params = GridLayout.LayoutParams()
            params.rowSpec = GridLayout.spec(0)
            params.columnSpec = GridLayout.spec(i, 1f)
            params.width = 0
            params.height = GridLayout.LayoutParams.WRAP_CONTENT
            params.setGravity(Gravity.FILL_HORIZONTAL)
            textView.layoutParams = params
            calendarGrid.addView(textView)
        }

        // 添加日期
        var row = 0
        var column = firstDayOfWeek
        for (day in 1..daysInMonth) {
            if (column == 0) {
                // 添加分隔线
                val divider = View(this)
                val dividerParams = GridLayout.LayoutParams()
                dividerParams.rowSpec = GridLayout.spec(row)
                dividerParams.columnSpec = GridLayout.spec(0, 7)
                dividerParams.width = GridLayout.LayoutParams.MATCH_PARENT
                dividerParams.height = 4 // 分隔线高度
                divider.setBackgroundColor(resources.getColor(android.R.color.darker_gray))
                divider.layoutParams = dividerParams
                calendarGrid.addView(divider)
                row++
            }
            val textView = TextView(this)
            textView.setTextColor(Color.rgb(172,172,255))
            textView.setTypeface(null, Typeface.BOLD)
            textView.text = day.toString()
            textView.textSize = 32f
            textView.textAlignment = TextView.TEXT_ALIGNMENT_CENTER
            // 如果是本年月且是本日，将日期设置为红色
            if (year == currentYear && month == currentMonth && day == currentDay) {
                textView.setTextColor(Color.RED)
                textView.textSize = 48f
            }
            val params = GridLayout.LayoutParams()
            params.rowSpec = GridLayout.spec(row)
            params.columnSpec = GridLayout.spec(column, 1f)
            params.width = 0
            params.height = GridLayout.LayoutParams.WRAP_CONTENT
            params.setGravity(Gravity.FILL_HORIZONTAL)
            params.setMargins(0, 80, 0, 80) // 调整行间距
            textView.layoutParams = params
            calendarGrid.addView(textView)
            // 设置日期点击事件
            textView.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        v.setBackgroundColor(Color.TRANSPARENT) // 松开时恢复背景颜色
                    }
                }
                false
            }
            textView.setOnClickListener {
                val intent = Intent(this, DayEventsActivity::class.java)
                intent.putExtra("year", year)
                intent.putExtra("month", (month + 1))
                intent.putExtra("day", day)
                startActivity(intent)
            }
            column++
            if (column == 7) {
                column = 0
                row++
            }
        }
        // 设置加号按钮点击事件
        val addButton: ImageView = findViewById(R.id.addate)
        addButton.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundColor(Color.LTGRAY) // 按下时改变背景颜色
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    v.setBackgroundColor(Color.TRANSPARENT) // 松开时恢复背景颜色
                }
            }
            false
        }
        addButton.setOnClickListener {
            showAddMemoDialog(year.toString(), (month + 1).toString())
        }
    }

    private fun showAddMemoDialog(year: String, month: String) {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("添加备忘录")

        val container = LinearLayout(this)
        container.orientation = LinearLayout.VERTICAL
        container.setPadding(50, 40, 50, 10)

        val typeSpinner = Spinner(this)
        val types = EventType.values().map { it.name }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, types)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        typeSpinner.adapter = adapter
        container.addView(typeSpinner)

        val titleInput = EditText(this)
        titleInput.hint = "标题"
        container.addView(titleInput)

        val descriptionInput = EditText(this)
        descriptionInput.hint = "描述"
        container.addView(descriptionInput)

        val yearInput = EditText(this)
        yearInput.hint = "年份"
        yearInput.setText(year)
        //不可更改
        yearInput.isEnabled = false
        container.addView(yearInput)

        val monthInput = EditText(this)
        monthInput.hint = "月份"
        monthInput.setText(month)
        monthInput.isEnabled = false
        container.addView(monthInput)

        val dayInput = EditText(this)
        dayInput.hint = "日期"
        container.addView(dayInput)


        builder.setView(container)
        builder.setPositiveButton("确定") { dialog, _ ->
            // 处理输入的数据
            val title = titleInput.text.toString()
            val description = descriptionInput.text.toString()
            val type = EventType.valueOf(typeSpinner.selectedItem.toString())
            val year = yearInput.text.toString()
            val month = monthInput.text.toString()
            val day = dayInput.text.toString()

            val dateEvent = DateEvent(
                title = title,
                description = description,
                dateyear = year,
                datemonth = month,
                dateday = day,
                type = type,
            )
            // 添加事件到 DateEventManager
            DateEventManager.addEvent(dateEvent, this)
            dialog.dismiss()
        }

        builder.setNegativeButton("取消") { dialog, _ ->
            dialog.cancel()
        }

        val dialog = builder.create()
        dialog.show()
    }

    private fun getZodiac(year: Int): String {
        val zodiacs = arrayOf(
            "猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊"
        )
        return zodiacs[year % 12]
    }
}